package com.invest.utils.email;

import com.google.common.collect.Maps;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.MailAuthenticationException;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;
import java.util.Map;

/**
 * <p>注释</p>
 *
 * @author yuyizhao
 * @version v0.1 2016/7/22 Exp
 */
@Service
public class SendEmailService {
    private static final Logger LOGGER = LoggerFactory.getLogger(SendEmailService.class);
    private static final String ENCODE= "UTF-8";
    private static final Map<String,String> EMAIL_PROP_MAP = Maps.newHashMap();
    private static final EmailHost HOST_QQ;
    private static final EmailHost HOST_163;
    private static final EmailHost HOST_SINA;
    static{
        EMAIL_PROP_MAP.put("mail.smtp.auth","true");
        EMAIL_PROP_MAP.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
        EMAIL_PROP_MAP.put("mail.smtp.socketFactory.port","465");
        EMAIL_PROP_MAP.put("mail.smtp.port","465");
        HOST_QQ = EmailHost.instance("smtp.qq.com",25,EMAIL_PROP_MAP);
        HOST_163 = EmailHost.instance("smtp.163.com",25,EMAIL_PROP_MAP);
        HOST_SINA = EmailHost.instance("smtp.sina.com",25,EMAIL_PROP_MAP);
    }

    /**
     * 发送邮件
     * @param request
     * @return
     */
    public SendEmailResult send(SendEmailRequest request){
        try{
            JavaMailSenderImpl javaMailSender = build(request);
            MimeMessagePreparator messagePreparator = prepare(request);
            javaMailSender.send(messagePreparator);
            return SendEmailResult.success();
        }catch (MailAuthenticationException ex){
            LOGGER.error("send email exception:",ex);
            return SendEmailResult.fail("用户名密码错误 或者 邮箱未开启POP3/SMTP服务！");
        }catch (Throwable ex){
            LOGGER.error("send email exception:",ex);
            return SendEmailResult.fail(StringUtils.left(ex.getMessage(),1000));
        }
    }

    private JavaMailSenderImpl build(SendEmailRequest request){
        JavaMailSenderImpl sender = new JavaMailSenderImpl();
        sender.setUsername(request.getFromEmail());
        sender.setPassword(request.getFromPassword());
        EmailHost emailHost = getEmailHost(request.getFromEmail());
        sender.setHost(emailHost.getHost());
        sender.setPort(emailHost.getPort());
        sender.setJavaMailProperties(emailHost.getProperties());
        sender.setDefaultEncoding(ENCODE);
        return sender;
    }

    private MimeMessagePreparator prepare(final SendEmailRequest request) {
       MimeMessagePreparator message = new MimeMessagePreparator() {
            @Override
            public void prepare(MimeMessage mimeMessage) throws Exception {
                MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, ENCODE);
                helper.setFrom(request.getFromEmail());
                helper.setTo(request.getToEmail());
                helper.setText(request.getContent() ,Boolean.TRUE);
                helper.setSubject(request.getSubject());
            }
        };
        return message;
    }

    private EmailHost getEmailHost(String fromEmail ){
        if(fromEmail.contains("163.com")){
            return HOST_163;
        }
        if(fromEmail.contains("qq.com")){
            return HOST_QQ;
        }
        if(fromEmail.contains("sina.com")){
            return HOST_SINA;
        }
       throw new IllegalArgumentException(fromEmail+"无法发送邮件!");
    }
}
